const express = require("express");
const TreeMenuModel = require("../models/treeMenuModel");
const router = express.Router();

/**
 * @swagger
 * /api/treeMenu:
 *   post:
 *     summary: 创建新的树形菜单
 *     tags: [树形菜单管理]
 *     responses:
 *       200:
 *         description: 创建成功的菜单对象
 *       500:
 *         description: 服务器错误
 */
router.post("/", async (req, res) => {
    try {
        const { name, tree } = req.body;
        const menu = await TreeMenuModel.create(name, tree);
        res.json(menu);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/**
 * @swagger
 * /api/treeMenu:
 *   get:
 *     summary: 获取所有树形菜单（排除已删除的）
 *     tags: [树形菜单管理]
 *     responses:
 *       200:
 *         description: 成功返回菜单列表
 *       500:
 *         description: 服务器错误
 */
router.get("/", async (req, res) => {
    try {
        const menus = await TreeMenuModel.findAll();
        res.json(menus);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/**
 * @swagger
 * /api/treeMenu/{id}:
 *   get:
 *     summary: 根据 ID 获取单个树形菜单
 *     tags: [树形菜单管理]
 *     responses:
 *       200:
 *         description: 返回对应的菜单对象
 *       404:
 *         description: 未找到对应菜单
 *       500:
 *         description: 服务器错误
 */
router.get("/:id", async (req, res) => {
    try {
        const menu = await TreeMenuModel.findById(req.params.id);
        if (!menu) return res.status(404).json({ error: "Not found" });
        res.json(menu);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/**
 * @swagger
 * /api/treeMenu/{id}:
 *   put:
 *     summary: 更新指定 ID 的树形菜单（可更新状态）
 *     tags: [树形菜单管理]
 *     responses:
 *       200:
 *         description: 更新成功
 *       404:
 *         description: 未找到对应菜单
 *       500:
 *         description: 服务器错误
 */
router.put("/:id", async (req, res) => {
    try {
        const { name, tree, status } = req.body;
        const success = await TreeMenuModel.update(req.params.id, name, tree, status);
        if (!success) return res.status(404).json({ error: "Not found" });
        res.json({ message: "Updated successfully" });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

/**
 * @swagger
 * /api/treeMenu/{id}:
 *   delete:
 *     summary: 软删除指定 ID 的树形菜单（status=2）
 *     tags: [树形菜单管理]
 *     responses:
 *       200:
 *         description: 删除成功（软删除）
 *       404:
 *         description: 未找到对应菜单
 *       500:
 *         description: 服务器错误
 */
router.delete("/:id", async (req, res) => {
    try {
        const success = await TreeMenuModel.delete(req.params.id);
        if (!success) return res.status(404).json({ error: "Not found" });
        res.json({ message: "Deleted successfully (soft delete)" });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
});

module.exports = router;
